import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Gio', '2.0')
gi.require_version('GLib', '2.0')
from gi.repository import Gtk, Gio, GLib
import threading

class MyWindow(Gtk.ApplicationWindow):
    def __init__(self, **kargs):
        super().__init__(**kargs, title='Hello World')

        box = Gtk.Box(spacing=6)
        self.set_child(box)

        button1 = Gtk.Button(label='Launch thread to trigger action')
        button1.connect('clicked', self.on_button1_clicked)
        box.append(button1)

    def on_button1_clicked(self, _widget):
        threading.Thread(target=trigger_action).start()

class MyApp(Gtk.Application):
    def __init__(self):
        super().__init__(application_id='org.example.MyApp')

        self.my_action_group = Gio.SimpleActionGroup()
        action = Gio.SimpleAction.new('my-action', GLib.VariantType.new('s'))
        action.connect('activate', self.on_my_action_activated)
        self.my_action_group.add_action(action)

    def on_my_action_activated(self, action: Gio.SimpleAction, parameter):
        print(f"Action triggered! action: {action.props.name}, parameter: {parameter}")
    
    def do_activate(self):  # 实现activate信号处理函数以显示窗口等操作
        win = MyWindow(application=app)
        win.present()  # 显示窗口
        win.connect("destroy", lambda w: Gtk.main_quit())  # 窗口关闭时退出程序
        win.present()  # 显示窗口内容（如果有的话）
    
    def do_startup(self):
        Gtk.Application.do_startup(self)
        GLib.set_application_name("My GTK4 App")
    
def trigger_action():
    print("Going to trigger action from thread.")
    parameter = GLib.Variant('s', 'Hello from thread!')
    GLib.idle_add(app.my_action_group.activate_action, 'my-action', parameter)

if __name__ == '__main__':
    app = MyApp()
    app.run()